﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrossLayerCommunication
{    
    public class Message : IMessage
    {
        #region IMessage
        public int Id { get; protected set; }

        public string Key { get; set; }

        public object[] Params { get; set; }

        public MessageType Type { get; protected set; }        

        public bool Equals(IMessage other)
        {
            if (other == null)
                return false;

            return Id == other.Id;
        }

        public object Clone()
        {
            return this.MemberwiseClone();
        }
        #endregion

        #region Constructor
        protected internal Message(int id, string key, MessageType type, params object[] args)
        {
            Id = id;
            Key = key;
            Params = args;
            Type = type;
        }
        #endregion

        #region Static
        internal static ConcurrentDictionary<int, IMessage> AllMessages = new ConcurrentDictionary<int, IMessage>();

        public static bool TryGetMessageById(int id, out IMessage message)
        {
            message = null;
            if (AllMessages.TryGetValue(id, out message))
            {
                message = (IMessage)message.Clone();
                return true;
            }

            return false;
        }

        #region Create
        public static IMessage Create(IMessage message)
        {
            AllMessages.AddOrUpdate(message.Id, message, (i, oldMessage) => { throw new Exception("Key already exists: " + i); });
            return message;
        }

        public static IMessage Create(int id, string key = null, MessageType type = MessageType.Error, params object[] arguments)
        {
            return Create(new Message(id, key, type, arguments));
        }
        #endregion
        #endregion
    }
}
